package io.shdxhl.simplerpc.code.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.shdxhl.simplerpc.code.netty.request.RpcRequest;
import io.shdxhl.simplerpc.code.utils.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 二次 Request 解码
 */
@Slf4j
public class RpcRequestDecoder extends MessageToMessageDecoder<ByteBuf> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        try {
            int length = byteBuf.readableBytes();
            byte[] body = new byte[length];
            byteBuf.readBytes(body);

            RpcRequest request = ProtostuffUtil.deserialize(body, RpcRequest.class);
            list.add(request);
        } catch (Exception e) {
            log.error("RpcRequestDecoder decoder error , msg={}", e.getMessage());
            throw new RuntimeException(e);
        }

    }
}
